package com.electric.qrapp.ui.file.newfile

import android.os.Bundle
import android.widget.FrameLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.electric.qrapp.R
import com.electric.qrapp.databinding.ActivityNewFileBinding
import com.electric.qrapp.entity.init.X5init
import com.electric.qrapp.ui.base.act.BaseActivity
import com.electric.qrapp.utils.function.NetUtils
import com.electric.qrapp.utils.function.init
import com.electric.qrapp.utils.system.Constants
import com.electric.qrapp.utils.system.toast
import com.electric.qrapp.utils.view.LoadingUtils
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsReaderView
import dagger.hilt.android.AndroidEntryPoint
import java.io.File

@AndroidEntryPoint
class NewFileActivity : BaseActivity<ActivityNewFileBinding>(), TbsReaderView.ReaderCallback {
    companion object {
        const val FILE_URL = "img_path"
    }

    private var mTbsReaderView: TbsReaderView? = null

    private val vm: NewFileViewModel by viewModels()

    override fun getLayoutId(): Int = R.layout.activity_new_file

    override fun initView() {
        dataBinding.wv.init(this, null, LoadingUtils(), true)
        initListener()
    }

    private fun initListener() {
        lifecycle.addObserver(object : LifecycleEventObserver {
            override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
                when (event) {
                    Lifecycle.Event.ON_DESTROY -> {
                        mTbsReaderView?.onStop()
                        QbSdk.closeFileReader(this@NewFileActivity)
                    }
                }
            }
        })

        vm.vmPreview.observe(this) {
            if (it.success) {
                previewFile(it.filePath, it.fileType)
            } else {
                toast("获取文件失败,请稍后再试")
            }
        }

        vm.loadingLiveDate.observe(this) {
            vm.loading(this, it)
        }
    }

    /**
     *文件预览
     * @param filePath 本地文件地址
     */
    private fun previewFile(filePath: String, fileType: String) {
        if (mTbsReaderView == null) {
            mTbsReaderView = TbsReaderView(this, this)
            dataBinding.fl.addView(
                mTbsReaderView,
                FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT
                )
            )
        }

        //增加下面一句解决没有TbsReaderTemp文件夹存在导致加载文件失败
        val bsReaderTempFile = File(Constants.File.TEMP_READ);
        if (!bsReaderTempFile.exists()) {
            val mkdir = bsReaderTempFile.mkdir();
            if (!mkdir) {
                toast("查看文档失败，请稍后重试")
                return
            }
        }


        val result = mTbsReaderView!!.preOpen(
            fileType,
            false
        )
        //支持的类型返回false 说明内核没有加载成功
        if (result) {
            val bundle = Bundle()
            bundle.putString(TbsReaderView.KEY_FILE_PATH, filePath)
            bundle.putString(TbsReaderView.KEY_TEMP_PATH, Constants.File.TEMP_READ);
            mTbsReaderView!!.openFile(bundle)
        } else {
            val params = HashMap<String, String>()
            params["local"] = "true"
            params["entryId"] = "2"
            params["allowAutoDestory"] = "true"
            QbSdk.openFileReader(this, filePath, params) {
                if (vm.isCloseFileRead(it)) {
                    this
                    QbSdk.closeFileReader(this)
                    finish()
                }
            }
        }
    }


    override fun initData() {
        if (!NetUtils.isNetworkConnected(this)) {
            val ab = AlertDialog.Builder(this)
            ab.setTitle("提示")
            ab.setMessage("未检测到网络,请检查网络连接!")
            ab.setPositiveButton("重试") { dialog, _ ->
                dialog.dismiss()
                initData()
            }
            ab.create().show()
            return
        }


        if (dataBinding.wv.x5WebViewExtension != null || X5init.installerCode == 200) {
            getFile()
            return
        }

        showLoad(true, "正在下载..")
        X5init.resetDownload(this) {
            showLoad(false)
            if (it) {
                getFile()
            } else {
                val ab = AlertDialog.Builder(this)
                ab.setTitle("提示")
                ab.setMessage("浏览器内核加载失败,请检查网络连接是否通畅!")
                ab.setPositiveButton("重试") { dialog, _ ->
                    dialog.dismiss()
                    initData()
                }
                ab.setNegativeButton("返回上一页") { dialog, _ ->
                    dialog.dismiss()
                    finish()
                }
                ab.create().show()
            }
        }

    }

    private fun getFile() {
        val filePath = intent.getStringExtra(FILE_URL)!!
        vm.getFile(this, filePath)
    }

    override fun setBindingData() {
    }


    override fun onCallBackAction(p0: Int?, p1: Any?, p2: Any?) {

    }


}